package org.gw.building.ctrl;

import jxl.Workbook;
import jxl.write.Label;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;
import jxl.write.WriteException;
import jxl.write.biff.RowsExceededException;
import org.apache.commons.lang3.StringUtils;
import org.gw.building.model.*;
import org.gw.building.repositories.dkgg.*;
import org.gw.building.util.FileHelper;
import org.gw.ylc.base.context.RequestContextHolder;
import org.gw.ylc.base.model.UserInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 *  考勤中心
    * @ClassName: KqyCtrl
    * @author liuyong
    * @date 2017年7月27日
 */
@RestController
@RequestMapping("kqc")
public class KqCenterCtrl {

	@Autowired
	private KcxxRepository kcxxRepository;

	@Autowired
	private QcxxRepository qcxxRepository;

	@Autowired
	private YbmxxRepository ybmxxRepository;

	@Autowired
	private DkxxRepository dkxxRepository;

	@Autowired
	private KqxxRepository kqxxRepository;

	@RequestMapping(value = "listKc")
	@ResponseBody
	public Page<Kcxx> queryKcList(String qc, String mc, String kksj) {
		UserInfo userInfo = RequestContextHolder.get().getUser();
		String departmentId = userInfo.getDepartment();
		if (StringUtils.isEmpty(departmentId) && userInfo.getType() != 1) {
			throw new RuntimeException("该用户没有权限");
		}

		if (!StringUtils.isEmpty(mc)) {
            mc = "%" + mc + "%";
        }

        if (StringUtils.equals("0", qc)) {
		    qc = null;
        }
		Page<Kcxx> kcs =  kcxxRepository.queryPage(qc, mc, kksj, RequestContextHolder.get().getPageRequest());
		return kcs;
	}

	@RequestMapping(value = "listQc")
	@ResponseBody
	public Page<Qcxx> querylistQc() {
		UserInfo userInfo = RequestContextHolder.get().getUser();
		String departmentId = userInfo.getDepartment();
		if (StringUtils.isEmpty(departmentId) && userInfo.getType() != 1) {
			throw new RuntimeException("该用户没有权限");
		}
		Page<Qcxx> qcs =  qcxxRepository.queryPage(RequestContextHolder.get().getPageRequest());
		return qcs;
	}

	@RequestMapping(value = "/queryKc")
	public Kcxx queryKc(String id){
		Kcxx entity = kcxxRepository.getOne(id);
		return entity;
	}

	@RequestMapping(value = "listYbm")
	@ResponseBody
	public Page<Kqxx> querylistYbm(String kcId, String xhgh, String status) {
		UserInfo userInfo = RequestContextHolder.get().getUser();
		String departmentId = userInfo.getDepartment();
		if (StringUtils.isEmpty(departmentId) && userInfo.getType() != 1) {
			throw new RuntimeException("该用户没有权限");
		}

		if (!StringUtils.isEmpty(xhgh)) {
			xhgh = "%" + xhgh + "%";
		}
		String dao = "0";
		String tui = "0";

		if (StringUtils.equals("1", status)) {
			dao = "1";
		} else if (StringUtils.equals("2", status)) {
			dao = "10";
		} else if (StringUtils.equals("3", status)) {
			tui = "1";
		} else if (StringUtils.equals("4", status)) {
			tui = "10";
		}

		Page<Kqxx> qcs =  kqxxRepository.queryKqPage(kcId, xhgh, dao, tui,RequestContextHolder.get().getPageRequest());
		return qcs;
	}

	@RequestMapping("addKqByType")
	@Transactional
	@ResponseBody
	public Object addKqByType(Dkxx entity, String type, String kqId) {
		//type 1表示签到  2表示签退
		if (!StringUtils.isEmpty(entity.getKc()) && !StringUtils.isEmpty(entity.getXhgh()) && !StringUtils.isEmpty(type)) {
			entity.setDksj(new Date());

			Kqxx kqxx = null;
			List<Kqxx> kList = this.kqxxRepository.queryKqByKcAndXh(entity.getKc(), entity.getXhgh());
			if (kList != null && !kList.isEmpty()) {
				kqxx = kList.get(0);
			} else {
				kqxx = new Kqxx();
				kqxx.setXhgh(entity.getXhgh());
				kqxx.setKc(entity.getKc());
				kqxx.setXm(entity.getXm());
			}

			if (StringUtils.equals("1", type) || StringUtils.equals("2", type)) {
				entity.setDkbz(type);
				dkxxRepository.save(entity);

				if (StringUtils.equals("1", type)) {
					//签到
					kqxx.setQiandao("1");
					kqxxRepository.save(kqxx);
				}

				if (StringUtils.equals("2", type)) {
					//签退
					kqxx.setQiantui("1");
					kqxxRepository.save(kqxx);
				}
			}
			return entity;
		}
		return null;
	}

	@RequestMapping("addQingjia")
	@Transactional
	@ResponseBody
	public Object addQingjia(Kqxx entity) {
		if (!StringUtils.isEmpty(entity.getKc()) && !StringUtils.isEmpty(entity.getXhgh())) {
			Kqxx kqxx = null;
			List<Kqxx> kList = this.kqxxRepository.queryKqByKcAndXh(entity.getKc(), entity.getXhgh());
			if (kList != null && !kList.isEmpty()) {
				kqxx = kList.get(0);
				this.kqxxRepository.updateQingJiaInfo(kqxx.getId());
			} else {
				kqxx = new Kqxx();
				kqxx.setXhgh(entity.getXhgh());
				kqxx.setKc(entity.getKc());
				kqxx.setXm(entity.getXm());
				kqxx.setDkbz("2");
				kqxxRepository.save(kqxx);
			}
			return entity;
		}
		return null;
	}

	@RequestMapping("addKaoqing")
	@Transactional
	@ResponseBody
	public Object addKaoqing(Kcxx entity) {
		if (!StringUtils.isEmpty(entity.getId())) {
			//正常考勤
			kqxxRepository.updateKaoqingZhengChang(entity.getId());

			//缺勤
			kqxxRepository.updateKaoqingQueQing(entity.getId());
			return entity;
		}
		return null;
	}

    //导出考勤信息
	@RequestMapping("exportKaoQinInfo")
	@ResponseBody
	public Object exportKaoQinInfo(String kcIds, String name, HttpServletResponse response)
			throws FileNotFoundException, IOException, RowsExceededException, WriteException {
		if (kcIds == null) {
			OutputStream out = response.getOutputStream();
			String o = "请选择课程后，再点击【导出考勤数据】";
			out.write(o.getBytes());
			out.flush();
			return null;
		}
		String[] kcs = kcIds.split(",");
		List<Kqxx> qcs =  kqxxRepository.queryKqByKc(kcs);
		File tempFolder = FileHelper.getTempFolder("train_");
		String showKcmc = "";
		Map<String, Kcxx> map = new HashMap<String, Kcxx>();
		if (kcs != null && kcs.length > 0) {
			for (String kid : kcs) {
				if (!StringUtils.isEmpty(kid)) {
					Kcxx kcxx = kcxxRepository.findOne(kid);
					if (kcxx != null) {
						map.put(kid, kcxx);
						showKcmc = kcxx.getKcmc();
					}
				}
			}
		}
		String xlsFileName = "课程-" + showKcmc + "考勤表.xls";
		String xlsFilePath = tempFolder.getAbsolutePath() + "/" + xlsFileName;
		File xlsFile = new File(xlsFilePath);
		response.setContentType("application/octet-stream;charset=UTF-8");
		response.setHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode(xlsFileName, "UTF-8"));
		doExportKaoQinInfo(xlsFile, qcs, map);
		OutputStream out = response.getOutputStream();
		FileCopyUtils.copy(new FileInputStream(xlsFile), out);
		out.flush();
		return null;
	}

	private void doExportKaoQinInfo(File xlsFile, List<Kqxx> kqxxList, Map<String, Kcxx> map)
			throws IOException, RowsExceededException, WriteException {
		WritableWorkbook book = null;
		String[] headers = { "学号", "姓名", "课程", "考勤状态" };
		try {
			book = Workbook.createWorkbook(xlsFile);
			WritableSheet sheet = book.createSheet("课程考勤表", 0);
			/** 写header */
			for (int i = 0; i < headers.length; i++) {
				sheet.addCell(new Label(i, 0, headers[i]));
			}
			int row = 1;
			for (Kqxx c : kqxxList) {
				try {
					sheet.addCell(new Label(0, row, c.getXhgh()));
					sheet.addCell(new Label(1, row, c.getXm()));

					String kcmc = "";
					Kcxx k = map.get(c.getKc());
					if (k != null) {
						kcmc = k.getKcmc();
					}
					sheet.addCell(new Label(2, row, kcmc));

					String zt = "";
					String kqzt = c.getDkbz();
					if (StringUtils.equals("1", kqzt)) {
						zt = "正常";
					} else if (StringUtils.equals("2", kqzt)) {
						zt = "请假";
					} else {
						zt = "缺勤";
					}
					sheet.addCell(new Label(3, row, zt));
				} catch (Exception e) {
				}
				row += 1;
			}
			book.write();
		} finally {
			if (book != null)
				try {
					book.close();
				} catch (WriteException e) {
					e.printStackTrace();
				} catch (IOException e) {
					e.printStackTrace();
				}
		}
	}

}
